package com.yksj.healthtalk.ui;

import java.util.HashMap;
import java.util.Map;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.http.JsonsfHttpResponseHandler;
import com.yksj.healthtalk.net.http.RequestParams;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.ui.dictionary.DictionarySecendActivity;
import com.yksj.healthtalk.ui.doctor.DoctorSearchResultActivity;
import com.yksj.healthtalk.ui.friend.FriendSearchUI;
import com.yksj.healthtalk.ui.interestwall.InterestMainActivity;
import com.yksj.healthtalk.ui.salon.SalonMainUIActivity;
import com.yksj.healthtalk.utils.ToastUtil;
/**
 * 全局搜素
 * @author jack_tang
 *
 */
public class SearchDialogFragment extends DialogFragment implements
		OnItemClickListener {

	final Map<String, JSONArray> mCacheMap = new HashMap<String, JSONArray>();
	ListView mListView;
	ResultAdapter mAdapter;
	EditText mEditText;
	final DisplayMetrics metrics = new DisplayMetrics();

	public static void onShowDialog(FragmentManager manager) {
		new SearchDialogFragment().show(manager, "search");
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setStyle(STYLE_NO_FRAME, android.R.style.Theme_Translucent_NoTitleBar);
		getActivity().getWindowManager().getDefaultDisplay()
				.getMetrics(metrics);

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.search_dialog_layout, null);
		mListView = (ListView) view.findViewById(android.R.id.list);
		View emptyView = view.findViewById(R.id.list_empty);
		mListView.setEmptyView(emptyView);

		mEditText = (EditText) view.findViewById(R.id.search_input);
		mEditText.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				if (s.length() == 0) {
					mAdapter.clear();
					return;
				}
				onSearch(s.toString());
			}
		});
		emptyView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dismissAllowingStateLoss();
			}
		});
		view.findViewById(R.id.cancel).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View v) {
						dismissAllowingStateLoss();
					}
				});
		mListView.setOnItemClickListener(this);
		
		mEditText.requestFocus();                       // EditText获得焦点  
        getDialog().getWindow().setSoftInputMode( LayoutParams.SOFT_INPUT_STATE_VISIBLE); // 显示软键盘  
		return view;
	}

	@Override
	public void onActivityCreated(Bundle arg0) {
		super.onActivityCreated(arg0);
		mAdapter = new ResultAdapter();
		mListView.setAdapter(mAdapter);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		JSONObject object = mAdapter.getItem(position);
		String ID = object.getString("ID");
		Intent intent;
		switch (Integer.valueOf(ID)) {
		case 1://专家医生
			intent = new Intent(getActivity(), DoctorSearchResultActivity.class);
			intent.putExtra("result", mEditText.getText().toString());
			startActivity(intent);
			break;
		case 2://药品购买
			intent = new Intent(getActivity(), ServerCenterListActivity.class);
			intent.putExtra("json", object.toString());
			intent.putExtra("title", object.getString("NAME"));
			intent.putExtra("result", mEditText.getText().toString());
			intent.putExtra("type", 4);
			startActivity(intent);
			break;
		case 3://沙龙讨论
			intent = new Intent(getActivity(), SalonMainUIActivity.class);
			intent.putExtra("groupName", mEditText.getText().toString());
			startActivity(intent);
			break;
		case 4://朋友交流
			intent = new Intent(getActivity(), FriendSearchUI.class);
			intent.putExtra("duoMeiNum", mEditText.getText().toString());
			startActivity(intent);
			break;
		case 5://个人发布
			intent = new Intent(getActivity(), InterestMainActivity.class);
			intent.putExtra("NAME", mEditText.getText().toString());
			startActivity(intent);
			break;
		case 6:

			break;
		case 7://症状
			intent = new Intent(getActivity(), DictionarySecendActivity.class);
			intent.putExtra("title", object.getString("NAME"));
			intent.putExtra("keyname", mEditText.getText().toString());
			intent.putExtra("parame", "-101");
			startActivity(intent);
			break;
		case 8://疾病
			intent = new Intent(getActivity(), DictionarySecendActivity.class);
			intent.putExtra("title", object.getString("NAME"));
			intent.putExtra("keyname", mEditText.getText().toString());
			intent.putExtra("parame", "-100");
			startActivity(intent);
			break;
		case 9://医院机构
			intent = new Intent(getActivity(), ServerCenterSeachListActivity.class);
			intent.putExtra("type",ID);
			intent.putExtra("json", object.toString());
			intent.putExtra("title", object.getString("NAME"));
			intent.putExtra("value", mEditText.getText().toString());
			startActivity(intent);
			break;
		case 10://保健服务
			intent = new Intent(getActivity(), ServerCenterSeachListActivity.class);
			intent.putExtra("type",ID);
			intent.putExtra("json", object.toString());
			intent.putExtra("title", object.getString("NAME"));
			intent.putExtra("value", mEditText.getText().toString());
			startActivity(intent);
			break;
		case 11://学者协会
			intent = new Intent(getActivity(), ServerCenterSeachListActivity.class);
			intent.putExtra("type", ID);
			intent.putExtra("json", object.toString());
			intent.putExtra("title", object.getString("NAME"));
			intent.putExtra("value", mEditText.getText().toString());
			startActivity(intent);
			break;
		case 12://医药商家
			intent = new Intent(getActivity(), ServerCenterSeachListActivity.class);
			intent.putExtra("type", ID);
			intent.putExtra("json", object.toString());
			intent.putExtra("title", object.getString("NAME"));
			intent.putExtra("value", mEditText.getText().toString());
			startActivity(intent);
			break;
		case 13://行业协会
			intent = new Intent(getActivity(), ServerCenterSeachListActivity.class);
			intent.putExtra("type", ID);
			intent.putExtra("json", object.toString());
			intent.putExtra("title", object.getString("NAME"));
			intent.putExtra("value", mEditText.getText().toString());
			startActivity(intent);
			break;
		case 14://科室
			requstDictionary(mEditText.getText().toString());
			break;
		}
	}
	
	/**
	 * 科室
	 */
	private void requstDictionary(final String keyWords){
		RequestParams params=new RequestParams();
		params.put("nameKeys", keyWords);
		HttpRestClient.doHttpURL_QUERYOFFICESSERVLET(params,new JsonsfHttpResponseHandler(getActivity()){
			@Override
			public void onSuccess(int statusCode, JSONObject response) {
				super.onSuccess(statusCode, response);
				if(!TextUtils.isEmpty(response.toString())){
					Intent intent =new Intent(getActivity(),DictionarySecendActivity.class);
					intent.putExtra("parame", "4");
					intent.putExtra("title", "科室");
					intent.putExtra("responseContent", response.toString());
					startActivity(intent);	
				}
			}
		});
	}
	
	private void onSearch(final String str) {
		if (mCacheMap.containsKey(str)) {
			mAdapter.onBountData(mCacheMap.get(str));
		} else {
			RequestParams params = new RequestParams();
			params.put("OPTION", "ALL");
			params.put("KEYWORDS", str);
			params.put("CUSTID", SmartFoxClient.getLoginUserId());
			HttpRestClient.doHttpHomePageQueryServlet(params,
					new JsonsfHttpResponseHandler() {
						@Override
						public void onSuccess(int statusCode,JSONObject response) {
							if (response.containsKey("error_message")) {
								ToastUtil.showShort(response.getString("error_message"));
							} else {
								JSONArray jsonArray = response.getJSONArray("RESULT");
								mCacheMap.put(str, jsonArray);
								if(str.equalsIgnoreCase(mEditText.getEditableText().toString())){
									mAdapter.onBountData(jsonArray);
								}
							}
						}
					});
		}
	}

	private class ResultAdapter extends BaseAdapter {
		final JSONArray jsonArray;
		final LayoutInflater inflater;

		public ResultAdapter() {
			inflater = getActivity().getLayoutInflater();
			jsonArray = new JSONArray();
		}

		@Override
		public int getCount() {
			return jsonArray.size();
		}

		private void clear() {
			jsonArray.clear();
			notifyDataSetChanged();
		}

		private void onBountData(JSONArray jsonArray) {
			this.jsonArray.clear();
			this.jsonArray.addAll(jsonArray);
			notifyDataSetChanged();
		}

		@Override
		public JSONObject getItem(int arg0) {
			return (JSONObject) jsonArray.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			return arg0;
		}

		@Override
		public View getView(int arg0, View contentView, ViewGroup group) {
			JSONObject jsonObject = getItem(arg0);
			ViewHolder holder;
			if (contentView == null) {
				holder = new ViewHolder();
				contentView = inflater.inflate(R.layout.main_seach_all_item,null);
				holder.icon = (ImageView) contentView.findViewById(R.id.icon_view);
				holder.name = (TextView) contentView.findViewById(R.id.name_type);
				holder.number = (TextView) contentView.findViewById(R.id.number);
				contentView.setTag(holder);
			} else {
				holder = (ViewHolder) contentView.getTag();
			}
			holder.icon.setVisibility(View.VISIBLE);
			holder.name.setText(jsonObject.getString("NAME"));
			holder.number.setText(jsonObject.getString("COUNT"));
			String path = jsonObject.getString("ICON");
				if(TextUtils.isEmpty(path))return contentView;
				
			if (path.contains("zhuanjia")) {
				holder.icon.setBackgroundResource(R.drawable.seach_zhuanjia);
			} else if (path.contains("yaopin")) {
				holder.icon.setBackgroundResource(R.drawable.seach_yaopin);
			} else if (path.contains("shalong")) {
				holder.icon.setBackgroundResource(R.drawable.seach_salon);
			} else if (path.contains("bingyou")) {
				holder.icon.setBackgroundResource(R.drawable.seach_bingyou);
			} else if (path.contains("fabu")) {
				holder.icon.setBackgroundResource(R.drawable.seach_fabu);
			} else if (path.contains("zhengzhuang")) {
				holder.icon.setBackgroundResource(R.drawable.seach_zhengzhuang);
			} else if (path.contains("jibing")) {
				holder.icon.setBackgroundResource(R.drawable.seach_jibing);
			} else if (path.contains("baojian")) {
				holder.icon.setBackgroundResource(R.drawable.seach_baojian);
			} else if (path.contains("yiyuan")) {
				holder.icon.setBackgroundResource(R.drawable.seach_yiyuan);
			} else if (path.contains("hangyexiehui")) {
				holder.icon.setBackgroundResource(R.drawable.seach_xiehui);
			} else if (path.contains("shangjia")) {
				holder.icon.setBackgroundResource(R.drawable.search_icon_shangjia);
			}else if (path.contains("search_icon_office")) {//科室
				holder.icon.setBackgroundResource(R.drawable.search_icon_office);
			} else {
				holder.icon.setVisibility(View.GONE);
			}
			return contentView;
		}

		private class ViewHolder {
			public ImageView icon;
			public TextView name;
			public TextView number;
		}
	}

}
